package com.youlu.campus.admin.utils;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;

/**
 * @author : [dengbo]
 * @className : LocalDateUtil
 * @description : [日期处理类]
 * @createTime : [2022/5/26 19:40]
 */
@Slf4j
public class LocalDateUtil {
    /**
     * localDateTime 序列化
     */
    public static class LocalDateTimeSerializer extends JsonSerializer<LocalDateTime> {

        @Override
        public void serialize(LocalDateTime localDateTime, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
            if (localDateTime != null) {
                long timestamp = getTimeStampByLocalDateTime(localDateTime);
                jsonGenerator.writeNumber(timestamp);
            }
        }
    }

    /**
     * localDateTime 反序列化
     */
    public static class LocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {

        @Override
        public LocalDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
            long timestamp = jsonParser.getValueAsLong();
            return getLocalDateTimeByTimeStamp(timestamp);
        }
    }

    public static long getTimeStampByLocalDateTime(LocalDateTime localDateTime) {
        ZoneId zone = ZoneOffset.of("+8");
        Instant instant = localDateTime.atZone(zone).toInstant();
        return instant.toEpochMilli();
    }

    public static LocalDateTime getLocalDateTimeByTimeStamp(long timestamp) {
        Instant instant = Instant.ofEpochMilli(timestamp);
        return LocalDateTime.ofInstant(instant, ZoneOffset.of("+8"));
    }
}
